using Microsoft.AspNetCore.Mvc;
using ERPBackend.Models;
using ERPBackend.Services;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ERPBackend.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class FirstLevelCategoriesController : ControllerBase
    {
        private readonly IFirstLevelCategoryService _firstLevelCategoryService;

        public FirstLevelCategoriesController(IFirstLevelCategoryService firstLevelCategoryService)
        {
            _firstLevelCategoryService = firstLevelCategoryService;
        }

        // GET: api/FirstLevelCategories
        [HttpGet]
        public async Task<ActionResult<IEnumerable<FirstLevelCategory>>> GetFirstLevelCategories()
        {
            var categories = await _firstLevelCategoryService.GetAllFirstLevelCategoriesAsync();
            return Ok(categories);
        }

        // GET: api/FirstLevelCategories/5
        [HttpGet("{id}")]
        public async Task<ActionResult<FirstLevelCategory>> GetFirstLevelCategory(int id)
        {
            var firstLevelCategory = await _firstLevelCategoryService.GetFirstLevelCategoryByIdAsync(id);

            if (firstLevelCategory == null)
            {
                return NotFound();
            }

            return firstLevelCategory;
        }

        // PUT: api/FirstLevelCategories/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutFirstLevelCategory(int id, FirstLevelCategory firstLevelCategory)
        {
            if (id != firstLevelCategory.Id)
            {
                return BadRequest();
            }

            var updated = await _firstLevelCategoryService.UpdateFirstLevelCategoryAsync(firstLevelCategory);
            if (!updated)
            {
                return NotFound();
            }

            return NoContent();
        }

        // POST: api/FirstLevelCategories
        [HttpPost]
        public async Task<ActionResult<FirstLevelCategory>> PostFirstLevelCategory(FirstLevelCategory firstLevelCategory)
        {
            var createdCategory = await _firstLevelCategoryService.CreateFirstLevelCategoryAsync(firstLevelCategory);
            return CreatedAtAction("GetFirstLevelCategory", new { id = createdCategory.Id }, createdCategory);
        }

        // DELETE: api/FirstLevelCategories/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteFirstLevelCategory(int id)
        {
            var deleted = await _firstLevelCategoryService.DeleteFirstLevelCategoryAsync(id);
            if (!deleted)
            {
                // 如果删除失败，可能是因为分类不存在或有相关的二级分类
                return NotFound();
            }

            return NoContent();
        }
    }
}